package edu.scau.web.pos;

import com.alipay.api.AlipayApiException;
import com.fasterxml.jackson.core.JsonProcessingException;
import edu.scau.core.Enum.OrderStatus;
import edu.scau.core.constants.AjaxResult;
import edu.scau.core.constants.HttpStatus;
import edu.scau.core.exection.BusinessProcessException;
import edu.scau.payment.service.PaymentService;
import edu.scau.pos.domain.Orders;
import edu.scau.pos.domain.Sale;
import edu.scau.pos.service.SaleService;
import edu.scau.pos.vo.SaleLineItemVo;
import edu.scau.pos.vo.SaleVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@Tag(name = "销售业务管理",description = "销售业务流程")
@RequestMapping("/sale")
public class SaleController {
    @Autowired
    private SaleService saleService;
    @Autowired
    private PaymentService paymentService;

    @Operation(
            summary = "1. 开启销售",
            description = "开启销售,返回saleId,访问权限:admin、cashier",
            responses = {
                    @ApiResponse(description = "saleId:销售流程id")
            }
    )
    /**
     * 开启销售
     * @return saleId currentSale的key
     */
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    @GetMapping("/startNewSale")
    public AjaxResult startNewSale(){
        String saleId=saleService.startNewSale();
        Map<String, Object> data = new HashMap<>();
        data.put("saleId",saleId);
        return AjaxResult.success(data);
    }

    /**
     *通过商品sn查找库存
     * @param productSn 商品编号
     * @return stock 库存
     */
    @Operation(
            summary = "2. 查询商品库存",
            description = "通过productSn查询单个商品的库存,返回stock, 访问权限:admin、cashier",
            parameters = {
                    @Parameter(name = "productSn", description = "productSn", required = true, schema = @Schema(type = "String"))
            },
            responses = {
            @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))),
            @ApiResponse(responseCode = "304", description = "请求参数错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
    }
    )
    @GetMapping("/getProductStock")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult getProductStock(@RequestParam("productSn") String productSn){
          Map<String, Object> data = new HashMap<>();
          int stock= saleService.getProductStock(productSn);
          data.put("stock",stock);
          return AjaxResult.success(data);
    }

    /**
     *通过商品sn查找库存
     * @param saleLineItemVo 商品编号
     * @return stock 库存
     */
    @Operation(
            summary = "3. 加购商品判断库存",
            description = "加购商品,判断库存,返回stock, 访问权限:admin、cashier",
//            parameters = {
//                    @Parameter(name = "productSn", description = "productSn", required = true, schema = @Schema(type = "String")),
//                    @Parameter(name = "quantity", description = "加购商品数量", required = true, schema = @Schema(type = "int"))
//            },
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class))),
                    @ApiResponse(responseCode = "304", description = "请求参数错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    @PostMapping("/judgeStock")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult judgeStock(@Validated  @RequestBody SaleLineItemVo saleLineItemVo){
            if(saleService.judgeStock(saleLineItemVo)){
                return AjaxResult.success("库存充足");
            }
            return AjaxResult.success("库存不足，无法加购！");
    }

    /**
     * 结束销售,返回销售总额、数量,saleI必需属性
     * @param saleVo
     * @return saleResult
     */
    @Operation(
            summary = "4. 结束销售",
            description = "结束销售,返回销售总额、数量,saleI必需属性, 访问权限:admin、cashier",
            responses = {

                    @ApiResponse( responseCode = "orderId", description = "订单ID"),
                    @ApiResponse( responseCode = "orderAmount", description = "订单总金额"),
                    @ApiResponse( responseCode = "quantity", description = "订单商品数量"),
                    @ApiResponse( responseCode = "status", description = "订单状态", content = @Content( mediaType = "application/json", schema = @Schema(implementation = OrderStatus.class))),
            }
    )
    @PostMapping("/endSale")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult endSale(@Validated @RequestBody SaleVo saleVo){
           Map<String,Object> data=saleService.endSale(saleVo);
           return AjaxResult.success(data);
    }

    /**
     * 支付订单
     * @param saleId
     * @return 200
     */
    @Operation(
            summary = "5. 支付订单",
            description = "支付订单,返回codeId,saleI必需属性, 访问权限:admin、cashier",
            responses = {
                    @ApiResponse(description = "返回form表单,前端转译后插入页面"),
                    @ApiResponse(description = "/page/pay,另一个接口,由后端返回html,无需前端插入表单")
            }
    )
    @GetMapping("/makePayment")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult makePayment(@RequestParam("saleId") String saleId){
       try {
           String res= saleService.makePayment(saleId);
           return AjaxResult.success(res);
       } catch (AlipayApiException e){
           e.printStackTrace();
           return AjaxResult.error();
       }catch (JsonProcessingException e){
           e.printStackTrace();
           return AjaxResult.error();
       }
    }

    @Operation(
            summary = "6. 查看订单支付详情",
            description = "查看订单支付详情,返回订单支付详情, 访问权限:admin、cashier",
            responses = {
                    @ApiResponse(description = "务必显性或隐性调用该接口,协助后端完成入库"),
            }
    )
    @GetMapping("/checkOrderStatus")
    @PreAuthorize("hasAnyAuthority('admin','cashier')")
    public AjaxResult checkOrderStatus(@RequestParam("saleId") String saleId){
        try {
            Map data= saleService.checkOrderStatus(saleId);
            return AjaxResult.success(data);
        } catch (AlipayApiException e){
            log.info(e.getErrMsg());
            return AjaxResult.error();
        }catch (JsonProcessingException e){
            log.info(e.getOriginalMessage());
            return AjaxResult.error();
        }
    }

}
